﻿using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.SessionState;

using LMSemir.Entity;
using LMSemir.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace LMSemir.WebService
{
    /// <summary>
    /// LMSemirAPI 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Description = "注意：接口采用JSON作为传输的数据格式.")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class LMSemirAPI : System.Web.Services.WebService, IReadOnlySessionState
    {
        public CredentialSoapHeader csh = new CredentialSoapHeader();
        public readonly string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["LMSemirConnectionString"].ConnectionString;

        [SoapHeader("csh")]
        [WebMethod(Description = "新增TEE实体信息.", EnableSession = true)]
        public string AddTeeInfo(string Name, string Author,
            string Address, string VideoPath,
            string Email, string Mobile, string Intro,
            byte[] LargeImage, byte[] MiddImage, int Status,
            byte[] SmallImage, string Source,
            int UserID, string PhotoName, string PhotoPath)
        {
            int iCount = 0;
            string strMessage = string.Empty;
            string strReturn = string.Empty;

            string strSmallPath = string.Empty;
            string strMiddPath = string.Empty;
            string strLargePath = string.Empty;

            if (null != Name && null != Author && SmallImage.Length != 0 && MiddImage.Length != 0 &&
                Name.Length != 0 && Author.Length != 0 && LargeImage.Length != 0 &&
                csh.IsValid(out strMessage))
            {
                #region 保存图片到目录
                //获取存放图片文件名称
                string phsisPath = Server.MapPath("~/images/");
                string yearPath = phsisPath + DateTime.Now.Year + "\\";
                if (!Directory.Exists(yearPath))
                {
                    Directory.CreateDirectory(yearPath);
                }
                string monthPath = yearPath + DateTime.Now.Month + "\\";
                if (!Directory.Exists(monthPath))
                {
                    Directory.CreateDirectory(monthPath);
                }
                string dayPath = monthPath + DateTime.Now.Day + "\\";
                if (!Directory.Exists(dayPath))
                {
                    Directory.CreateDirectory(dayPath);
                }
                string smallDir = dayPath + "s\\";
                string middDir = dayPath + "m\\";
                string largeDir = dayPath + "l\\";
                if (!Directory.Exists(smallDir))
                {
                    Directory.CreateDirectory(smallDir);
                }
                if (!Directory.Exists(middDir))
                {
                    Directory.CreateDirectory(middDir);
                }
                if (!Directory.Exists(largeDir))
                {
                    Directory.CreateDirectory(largeDir);
                }

                //保存小图
                strSmallPath = smallDir + DateTime.Now.Hour + DateTime.Now.Minute +
                     DateTime.Now.Second + PhotoName + ".jpg";
                //保存中图
                strMiddPath = middDir + DateTime.Now.Hour + DateTime.Now.Minute +
                     DateTime.Now.Second + PhotoName + ".jpg";
                //保存大图
                strLargePath = largeDir + DateTime.Now.Hour + DateTime.Now.Minute +
                 DateTime.Now.Second + PhotoName + ".jpg";

                if (ImageUtils.SaveImgByPath(strSmallPath, SmallImage))
                {
                    if (ImageUtils.SaveImgByPath(strMiddPath, MiddImage))
                    {
                        if (ImageUtils.SaveImgByPath(strLargePath, LargeImage))
                        {
                            #region 拼接图片地址
                            int startLength = strSmallPath.IndexOf("images") - 1;
                            int endLength = strSmallPath.Length - strSmallPath.IndexOf("images") + 1;

                            strSmallPath = HttpContext.Current.Request.Url.Host +
                                strSmallPath.Substring(startLength, endLength).Replace("\\", "/");
                            strMiddPath = HttpContext.Current.Request.Url.Host +
                                strMiddPath.Substring(startLength, endLength).Replace("\\", "/");

                            #endregion

                            #region 保存TEE信息到DB
                            SqlParameter[] sqlParam = new SqlParameter[]{
                        new SqlParameter("@TName",Name.Trim ()),
                        new SqlParameter("@TAuthor",Author.Trim ()),
                        new  SqlParameter(@"TEmail",Email.Trim ()),
                        new  SqlParameter(@"TMobile",Mobile.Trim ()),
                        new SqlParameter("@TAddress",Address),
                        new SqlParameter("@TSource",TEEUtil.AnaylsisTeeSource(Source)),
                        new SqlParameter("@TIntro",Intro),
                        new SqlParameter("@TVideo",VideoPath),
                        new SqlParameter("@TPhotoPath",PhotoPath),
                        new SqlParameter("@TPhotoName",PhotoName),
                        new SqlParameter("@TSmallImage",strSmallPath),
                        new SqlParameter("@TMiddImage",strMiddPath),
                        new SqlParameter("@TLargeImage",strLargePath),
                        new SqlParameter("@TCreateTS",DateTime.Now),
                        new SqlParameter("@TUpdateTS",DateTime.Now),
                        new SqlParameter("@TUID",UserID)
                    };
                            iCount = SqlHelper.ExecuteNonQuery(strConn, "SP_TEEInfo_Add", sqlParam);
                            #endregion
                        }
                    }
                }

                #endregion
            }

            return strReturn = this.AnaylzsisImgUrl(iCount, strSmallPath, strMiddPath);
        }

        private string AnaylzsisImgUrl(int iCount, string smallUrl, string middUrl)
        {
            switch (iCount)
            {
                case 1:
                    return "{\"code\":\"1\",\"s_ImgUrl\": " + smallUrl + ",\"m_ImgUrl\":" + middUrl + "}";
                case -2:
                    return "{\"code\":\"-2\",\"s_ImgUrl\":\"\",\"m_ImgUrl\":\"\"}";
                default:
                    return "{\"code\":\"-1\",\"s_ImgUrl\":\" \",\"m_ImgUrl\":\"\"}";
            }
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "根据TEE编号,获取其实体信息.")]
        public string GetTeeInfoById(int TeeID)
        {
            string strMsg = string.Empty;
            string strJson = string.Empty;
            if (csh.IsValid(out strMsg))
            {
                StringBuilder strSelect = new StringBuilder();
                strSelect.AppendFormat("select * from tbTEEInfo te where te.TID={0}", TeeID);
                DataSet ds = SqlHelper.ExecuteDataset(strConn, CommandType.Text, strSelect.ToString());
                if (ds.Tables[0].Rows.Count > 0)
                {
                    strJson = JsonConvert.SerializeObject(ds.Tables[0], new DataTableConverter());
                }
            }
            return strJson;
        }

        [SoapHeader("csh")]
        [WebMethod(Description = "根据TEE编号,获取投票数")]
        public string GetVoteCountById(int TeeID)
        {
            string strMsg = string.Empty;
            string strVote = string.Empty;
            if (csh.IsValid(out strMsg))
            {
                if (TeeID > 0)
                {
                    //获取投票数
                    StringBuilder strSelect = new StringBuilder();
                    strSelect.AppendFormat("select TAVoteCount from tbTEEAttach ");
                    strSelect.AppendFormat("where TID={0} and TStatus=0", TeeID);

                    try
                    {
                        object obj = SqlHelper.ExecuteScalar(strConn, CommandType.Text, strSelect.ToString());
                        if (null != obj)
                        {
                            strVote = obj.ToString();
                        }
                        else
                        {
                            strVote = "-1";
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.GetInstance().WriteDebugLog("error:GetTeeVoteCount=>" + ex.Message);
                    }
                }
                else
                {
                    strVote = "TEE编号不合法.";
                }
            }
            return strVote;
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "分页获取TEE列表", EnableSession = true)]
        public string GetTeeListByPage(int pageIndex, int pageSize)
        {
            string strMsg = string.Empty;
            StringBuilder strJSON = new StringBuilder();
            StringBuilder strSelect = new StringBuilder();
            if (csh.IsValid(out strMsg))
            {
                SqlParameter[] sqlParam = new SqlParameter[]{
                    new SqlParameter("@TableName","tbTEEInfo"),
                    new SqlParameter("@Fields","*"),
                    new SqlParameter("@PrimaryKey","TID"),
                    new SqlParameter("@OrderField","TCreateTS"),
                    new SqlParameter("@Orderby","DESC"),
                    new SqlParameter("@sqlWhere"," "),
                    new SqlParameter("@pageSize",pageSize),
                    new SqlParameter("@pageIndex",pageIndex),
                    new SqlParameter("@readnum",100),
                    new SqlParameter("@TotalPage",ParameterDirection.Output)
                };
                try
                {
                    DataTable dt = SqlHelper.ExecuteDataset(strConn, "Paging2005", sqlParam).Tables[0];
                    strJSON.Append("{\"TEE\":\"" + JsonConvert.SerializeObject(dt, new DataTableConverter()) + "\"}");
                }
                catch (Exception ex)
                {
                    LogUtil.GetInstance().WriteDebugLog("error:GetTeeListByPage=>" + ex.Message);
                }
            }
            return strJSON.ToString();
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "根据TEE编号,设置投票数", EnableSession = true)]
        public string SetVoteCountByIds(int teeID, int voteCount, int userID)
        {
            string strMessage = string.Empty;
            string strCount = string.Empty;
            StringBuilder strInsert = new StringBuilder();
            if (csh.IsValid(out strMessage))
            {
                if (voteCount > 0 && teeID > 0 && userID > 0)
                {
                    StringBuilder strSelect = new StringBuilder();
                    strSelect.AppendFormat("select count(1) from tbTEEAttach where ");
                    strSelect.AppendFormat("TID={0} and TStatus=0 ", teeID);
                    int iCount = (int)SqlHelper.ExecuteScalar(strConn, CommandType.Text, strSelect.ToString());

                    if (iCount > 0)
                    {
                        StringBuilder strupdate = new StringBuilder();
                        strupdate.AppendFormat("update tbteeattach set ");
                        strupdate.AppendFormat("tavotecount={0},", voteCount);
                        strupdate.AppendFormat("tuid={0} ", userID);
                        strupdate.AppendFormat("where tid={0}", teeID);

                        int iupdate = SqlHelper.ExecuteNonQuery(strConn, CommandType.Text, strupdate.ToString());
                        strCount = iupdate == 1 ? "1" : "-1";
                    }
                    else
                    {
                        StringBuilder strIns = new StringBuilder();
                        strIns.AppendFormat("insert into tbTEEAttach(TID,TAVoteCount,TCreateTS,TUID,TUpdateTS,TStatus) ");
                        strIns.AppendFormat("values({0},{1},'{2}',", teeID, voteCount, DateTime.Now);
                        strIns.AppendFormat("{0},'{1}',{2})", userID, DateTime.Now, 0);

                        int taID = 0;
                        try
                        {
                            taID = SqlHelper.ExecuteNonQuery(strConn, CommandType.Text, strIns.ToString());
                        }
                        catch (Exception ex)
                        {
                            LogUtil.GetInstance().WriteDebugLog("error:insert tbTEEAttach's rowcount" + ex.Message);
                        }
                        strCount = taID > 0 ? "1" : "-1";
                    }
                }
            }
            return strCount;
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "根据作品名,作者名进行检索", EnableSession = true)]
        public string SearchTeeByKeyword(string query)
        {
            string strMsg = string.Empty;
            string strTeeList = string.Empty;
            StringBuilder strSelect = new StringBuilder();
            strSelect.AppendFormat("select tb.TName,tb.TAuthor from tbTEEInfo tb ");
            strSelect.AppendFormat("where contains(tb.TName,'{0}') ", query.Trim());
            strSelect.AppendFormat("or contains(tb.TAuthor,'{0}'); ", query.Trim());
            DataTable dt = SqlHelper.ExecuteDataset(strConn, CommandType.Text, strSelect.ToString()).Tables[0];
            if (dt.Rows.Count > 0)
            {
                strTeeList = JsonConvert.SerializeObject(dt, new DataTableConverter());
            }
            return strTeeList;
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "根据TEE分类编号,获取TEE信息列表")]
        public string GetTeeListById(int categoryID)
        {
            string strMsg = string.Empty;
            string strTeeList = string.Empty;
            if (csh.IsValid(out strMsg))
            {
                StringBuilder strSelect = new StringBuilder();
                strSelect.AppendFormat("select * from tbTEEInfo where TStatus=0 ");
                if (categoryID != 0)
                    strSelect.AppendFormat("and TSource={0}", categoryID);
                strSelect.AppendFormat(" order by TCreateTS DESC;");
                DataTable dt = SqlHelper.ExecuteDataset(strConn, CommandType.Text, strSelect.ToString()).Tables[0];

                if (dt.Rows.Count > 0)
                {
                    JsonSerializerSettings jss = new JsonSerializerSettings();
                    jss.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    strTeeList = JsonConvert.SerializeObject(dt, new DataTableConverter());
                }
            }
            return strTeeList;
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "获取最新的20条作品信息.")]
        public string GetTop20TeeList()
        {
            string strMsg = string.Empty;
            string strTeeList = string.Empty;
            if (csh.IsValid(out strMsg))
            {
                StringBuilder strTop20 = new StringBuilder();
                strTop20.AppendFormat("select top 20 * from tbTEEInfo ");
                strTop20.AppendFormat("order by TCreateTS desc");
                DataTable dt = SqlHelper.ExecuteDataset(strConn, CommandType.Text, strTop20.ToString()).Tables[0];

                if (dt.Rows.Count > 0)
                {
                    strTeeList = JsonConvert.SerializeObject(dt, new DataTableConverter());
                }
            }
            return strTeeList;
        }
        [SoapHeader("csh")]
        [WebMethod(Description = "获取前20名中奖的作品.(TStatus=2表示为已中奖)", EnableSession = true)]
        public string GetTeeListByWin20()
        {
            string strMsg = string.Empty;
            string strTeeList = string.Empty;
            if (csh.IsValid(out strMsg))
            {
                StringBuilder strTop20 = new StringBuilder();
                strTop20.AppendFormat("select top 20 * from tbTEEInfo ");
                strTop20.AppendFormat("where TStatus=2 ");
                strTop20.AppendFormat("order by TCreateTS desc");
                DataTable dt = SqlHelper.ExecuteDataset(strConn, CommandType.Text, strTop20.ToString()).Tables[0];

                if (dt.Rows.Count > 0)
                {
                    strTeeList = JsonConvert.SerializeObject(dt, new DataTableConverter());
                }
            }
            return strTeeList;
        }
    }
}